package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.AutoCatManager;
import com.fish.anne.model.AutoCat;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class AutoCatAction extends BaseAction implements Preparable {
    private AutoCatManager autoCatManager;
    private List autoCats;
    private AutoCat autoCat;
    private Long  catId;

    public void setAutoCatManager(AutoCatManager autoCatManager) {
        this.autoCatManager = autoCatManager;
    }

    public List getAutoCats() {
        return autoCats;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String autoCatId = getRequest().getParameter("autoCat.catId");
            if (autoCatId != null && !autoCatId.equals("")) {
                autoCat = autoCatManager.get(new Long(autoCatId));
            }
        }
    }

    public String list() {
        autoCats = autoCatManager.getAll();
        return SUCCESS;
    }

    public void setCatId(Long  catId) {
        this. catId =  catId;
    }

    public AutoCat getAutoCat() {
        return autoCat;
    }

    public void setAutoCat(AutoCat autoCat) {
        this.autoCat = autoCat;
    }

    public String delete() {
        autoCatManager.remove(autoCat.getCatId());
        saveMessage(getText("autoCat.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (catId != null) {
            autoCat = autoCatManager.get(catId);
        } else {
            autoCat = new AutoCat();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (autoCat.getCatId() == null);

        autoCatManager.save(autoCat);

        String key = (isNew) ? "autoCat.added" : "autoCat.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}